package org.jparrow.framework.proxy;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import net.sf.cglib.proxy.MethodProxy;

/**
 * 代理链
 * 
 * @author supda
 * @Date 2017-3-29 上午9:32:08
 *
 */
public class ProxyChain {

	//目标类
	private final Class<?> targetClass;
	//目标对象
	private final Object targetObject;
	//目标方法
	private final Method targetMethod;
	//方法代理
	private final MethodProxy methodProxy;
	//方法参数
	private final Object[] methodParams;

	//代理列表
	private List<Proxy> proxyList = new ArrayList<Proxy>();
	
	//代理索引
	private int proxyIndex = 0;

	public ProxyChain(Class<?> targetClass, Object targetObject,
			Method targetMethod, MethodProxy methodProxy,
			Object[] methodParams, List<Proxy> proxyList) {
		super();
		this.targetClass = targetClass;
		this.targetObject = targetObject;
		this.targetMethod = targetMethod;
		this.methodProxy = methodProxy;
		this.methodParams = methodParams;
		this.proxyList = proxyList;
	}
	
	/**
	 * 执行代理链
	 * 
	 */
	public Object doProxyChain() throws Throwable{
		Object methodResult;
		if(proxyIndex < proxyList.size()) {
			methodResult = proxyList.get(proxyIndex++).doProxy(this);
		}else{
			methodResult = methodProxy.invokeSuper(targetObject, 
					methodParams);
		}
		return methodResult;
	}
	

	public List<Proxy> getProxyList() {
		return proxyList;
	}

	public void setProxyList(List<Proxy> proxyList) {
		this.proxyList = proxyList;
	}

	public Class<?> getTargetClass() {
		return targetClass;
	}

	public Object getTargetObject() {
		return targetObject;
	}

	public Method getTargetMethod() {
		return targetMethod;
	}

	public Object[] getMethodParams() {
		return methodParams;
	}

}
